package com.xuecheng.content.service.impl;

import com.xuecheng.content.dto.CourseCategoryDto;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName CourseCategoryServiceImpl
 * @Description 查询课程分类实现类
 * @Author CG
 * @Date 2023/11/22 17:06
 **/
@Service("CourseCategoryService")
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryDto> queryTreeNodes(String id) {
        List<CourseCategoryDto> courseCategoryDto = courseCategoryMapper.selectTreeNodes(id);
        //将list转换为map，已备使用，排除跟节点
        Map<String, CourseCategoryDto> map = courseCategoryDto.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //最终返回的list
        List<CourseCategoryDto> courseCategoryDtoList = new ArrayList<>();
        //依次遍历每一个元素，排除根节点
        courseCategoryDto.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                courseCategoryDtoList.add(item);
            }
            //找到当前节点的父节点
            CourseCategoryDto courseCategoryDto1 = map.get(item.getParentid());
            if(courseCategoryDto1!=null){
                if(courseCategoryDto1.getChildrenTreeNodes() == null){
                    courseCategoryDto1.setChildrenTreeNodes(new ArrayList<CourseCategoryDto>());
                }
                //下面开始在ChildrenTreeNodes属性中放子节点
                courseCategoryDto1.getChildrenTreeNodes().add(item);
            }
        });

        return courseCategoryDtoList;
    }
}
